
package net.bingosoft.common.swato;

import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import net.bingosoft.common.json.JSONArray;
import net.bingosoft.common.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Zhijie Chen (zigzag.chen@gmail.com)
 */
public class JSONRequest extends HttpServletRequestWrapper {
	private static Log log = LogFactory.getLog(JSONRequest.class);

	private final static int buf_size = 4096;

	private JSONObject m_requestData;

	/**
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 * @throws ParseException
	 */
	public JSONRequest(HttpServletRequest req) {
		super(req);

		String charset = req.getCharacterEncoding();
		if (charset == null)
			charset = "UTF-8";
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charset));
			// Read the request
			CharArrayWriter data = new CharArrayWriter();
			char buf[] = new char[buf_size];
			int ret;
			while ((ret = in.read(buf, 0, buf_size)) != -1) {
				data.write(buf, 0, ret);
			}
			m_requestData = new JSONObject(data.toString());
		} catch (UnsupportedEncodingException e) {
			log.error(e);
			e.printStackTrace();
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
		} catch (ParseException e) {
			log.error(e);
			e.printStackTrace();
		}
		if (m_requestData != null) {
			log.debug("Received request:" + m_requestData.toString());
		}

	}

	/**
	 * @return Returns the serviceID.
	 */
	public String getId() {
		if (m_requestData != null) {
			return m_requestData.optString("id");
		} else {
			return null;
		}
	}

	/**
	 * @return Returns the connID.
	 */
	public int getConnId() {
		if (m_requestData != null) {
			return m_requestData.optInt("conn_id");
		} else {
			return 0;
		}
	}

	public String getMethodName() {
		if (m_requestData != null) {
			return m_requestData.optString("method");
		} else {
			return null;
		}
	}

	public JSONArray getParams() {
		if (m_requestData != null) {
			JSONArray paramArray = m_requestData.optJSONArray("params");
			if (paramArray.length() != 0) {
				return paramArray;
			}
		}
		return null;
	}
}
